<template>
  <base-modal :title="pageObj[dialogType] && pageObj[dialogType].title" :show.sync="visible" width="400px" class="base-import-modal">
    <div class="form-view-row" style="padding: 0">
      <label style="line-height: 32px">{{ pageObj[dialogType] && pageObj[dialogType].label }}</label>
      <div class="form-view-row-content flex-x">
        <!-- 产品类型 -->
        <el-cascader
          v-if="dialogType === 'linkCatalog'"
          :placeholder="$t('common.placeholder.select')"
          v-model="catalog"
          ref="formCascader"
          :options="catalogTree"
          :before-filter="beforeFilter"
          :show-all-levels="false"
          clearable
          expand-trigger="hover"
          style="width: 100%"
          :props="{
            value: 'id',
            label: 'name',
            children: 'tasks',
            expandTrigger: 'hover',
          }"
          filterable
        ></el-cascader>

        <el-select 
          v-else 
          v-model="nowChooseArr" 
          filterable 
          remote 
          collapse-tags 
          clearable 
          :placeholder="$t('common.placeholder.select')" 
          popper-class="max-w-488"
          @focus="remoteSelectSearchData" 
          :remote-method="remoteSelectSearchData" 
          :loading="selectLoading"
          class="flex-1 pos-r" 
        >
          <el-option 
            v-for="item in pageObj[dialogType] && pageObj[dialogType].options" 
            :key="item.id" :label="dialogType == 'linkQrcode' ? item.qrcodeId : item.pathName" 
            :value="dialogType == 'linkQrcode' ? item.qrcodeId : item.id"
          >
            <div class="flex-x overHideCon-1">
              <template v-if="dialogType == 'linkQrcode'">
                <div>{{ item.qrcodeId }}</div>
              </template>
              <template v-else>
                <div>{{ item.pathName }}</div>
              </template>
            </div>
          </el-option>
        </el-select>
      </div>
    </div>

    <div class="dialog-footer" style="margin-top: 15px">
      <el-button @click="visible = false">{{ $t('common.base.cancel') }}</el-button>
      <el-button type="primary" @click="bind" :loading="pending">{{ $t('common.base.contact2') }}</el-button>
    </div>
  </base-modal>
</template>

<script>
import { searchAllcatalog, cloneData, queryCatalogTree } from '@src/api/ProductV2Api';
import { getList } from '@src/api/productQrcode';
import _ from 'lodash';
import { Cascader } from 'element-ui';

export default {
  name: 'public-dialog',
  props: {
    productId: {
      type: String,
      default: '',
    },
    dialogType: {
      type: String,
      default: 'linkQrcode',
    },
  },
  watch: {
    visible(newVal, oldVal) {
      if (!newVal) {
        this.nowChooseArr = '';
        this.pending = false;
      }
    },
  },
  data() {
    return {
      visible: false,
      pending: false,
      selectLoading: false,
      nowChooseArr: '',
      pageObj: {
        linkQrcode: {
          title: this.$t('product.component.publicDialog.title1'),
          label: this.$t('product.component.publicDialog.label1'),
          http: getList,

          options: [],
        },
        linkCatalog: {
          title: this.$t('product.component.publicDialog.title2'),
          label: this.$t('product.component.publicDialog.label2'),
          http: searchAllcatalog,

          options: [],
        },
      },
      catalog: [],
      catalogTree: [],
    };
  },
  methods: {
    open() {
      this.visible = true;

      this.$nextTick(() => {
        if (this.dialogType === 'linkCatalog' && !this.catalogTree.length) {
          this.$watch('$refs.formCascader.inputValue', function (newVal, oldVal) {
            if(!newVal) {
              this.beforeFilter(newVal);
            }
          })
          this.getTreeList();
        }
      });
    },
    async getTreeList() {
      try {
        const { code, message, result } = await cloneData();
        if (code === 0) {
          this.deleteEmpty(result);
          this.catalogTree = result;
        } else {
          this.$platform.notification({
            type: 'error',
            title: this.$t('common.base.requestError'),
            message: message,
          });
        }
      } catch (err) {
        console.error(err);
      }
    },
    // 删除空子集
    deleteEmpty(list) {
      list.forEach(item => {
        if (!item.tasks.length) {
          delete item.tasks;
        } else {
          this.deleteEmpty(item.tasks);
        }
      });
    },
    close() {
      this.visible = false;
    },
    bind() {
      if (this.dialogType === 'linkCatalog') {
        if (!this.catalog.length) return this.$message.error(this.$t('product.component.publicDialog.tip1'));
        return this.$emit('dialogBind', { catalogId: this.catalog[this.catalog.length - 1] });
      }
      if (!this.nowChooseArr) return this.$message.error(this.$t('product.component.publicDialog.tip2'));

      this.pending = true;
      if (this.dialogType == 'linkQrcode') {
        this.$emit('dialogBind', { qrcodeId: this.nowChooseArr });
      } else {
        this.$emit('dialogBind', { catalogId: this.nowChooseArr });
      }
    },
    reset() {
      this.visible = false;
      this.nowChooseArr = '';
    },
    changeLoading(e) {
      this.pending = e;
    },

    remoteSelectSearchData: _.debounce(function (e) {
      this.selectLoading = true;
      let params = null;
      let keyWord = Object.prototype.toString.call(e) === '[object FocusEvent]' ? '' : e;
      if (this.dialogType === 'linkQrcode') {
        params = {
          keyword: keyWord,
          pageSize: 50,
          pageNum: 1,
          state: '0',
          productId: '',
          qrcodeId: '',
        };
      } else {
        params = {
          keyWord,
          pageSize: 50,
          pageNum: 1,
        };
      }
      this.pageObj[this.dialogType]
        .http(params)
        .then(res => {
          if (!res) {
            return;
          }
          if (this.dialogType === 'linkQrcode') this.pageObj[this.dialogType].options = res.data.list || [];
          else this.pageObj[this.dialogType].options = res.result.list || [];
        })
        .catch(err => {})
        .finally(() => {
          this.selectLoading = false;
        });
    }, 800),

    async beforeFilter (value) {
      if (!value) return this.getTreeList();

      try {
        const { code, message, result } = await queryCatalogTree({ keyWord: value });
        if (code === 0) {
          this.deleteEmpty(result);
          this.catalogTree = result;
        } else {
          this.$platform.notification({
            type: 'error',
            message: message
          })
        }
      } catch (err) {
        console.error(err);
      }
      
      return false;
    },
  },
  components: {
    [Cascader.name]: Cascader,
  },
};
</script>

<style lang="scss">
.el-radio {
  margin-bottom: 0;
}
.el-dialog__body {
  border-top: 1px solid rgba(0, 0, 0, 0.09);
  border-bottom: 1px solid rgba(0, 0, 0, 0.09);
  padding: 0;
}

.el-select-dropdown__item {
  height: auto;
}
.dialog-footer {
  display: flex;
  justify-content: flex-end;
}

.el-select-dropdown__empty {
  display: block !important;
}
</style>
